package org.ecype.diego;

import static org.ecype.diego.Uris.parseId;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class OneToManyProcessor extends AbstractUriProcessor {

	private final Reference reference;
	private final Uri childUri;

	public OneToManyProcessor(Reference reference) {
		this.reference = reference;
		childUri = reference.getChild().getUri();
	}

	@Override
	public String getType(Uri uri) {
		return provider.getType(reference.getChild().getUri());
	}

	@Override
	public Cursor query(Uri uri, Uri notifyUri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		return provider.query(childUri, notifyUri, projection, 
				andSelections(selection, whereParentIdIs(uri)), selectionArgs, sortOrder);
	}

	private String andSelections(String selection1, String selection2) {
        if (selection1 != null) {
            if (selection2 != null) {
                return "((" + selection1 + ") AND (" + selection2 + "))";
            } else {
                return selection1;
            }
        } else {
            return selection2;
        }
    }

    @Override
	public Uri insert(Uri uri, Uri notifyUri, ContentValues values) {
		values.put(reference.getLinkToParent(), parseId(uri));
		return provider.insert(reference.getChild().getUri(), notifyUri, values);
	}

	@Override
	public int bulkInsert(Uri uri, Uri notifyUri, ContentValues[] values) {
		for (ContentValues contVal : values) {
			contVal.put(reference.getLinkToParent(), parseId(uri));
		}
		return provider.bulkInsert(reference.getChild().getUri(), notifyUri, values);
	}
	
	@Override
	public int delete(Uri uri, Uri notifyUri, String selection, String[] selectionArgs) {
		return provider.delete(childUri, notifyUri, andSelections(selection, whereParentIdIs(uri)), selectionArgs);
	}
	
	@Override
	public int update(Uri uri, Uri notifyUri, ContentValues values, String selection, String[] selectionArgs) {
		return provider.update(childUri, notifyUri, values, andSelections(selection, whereParentIdIs(uri)), selectionArgs);
	}

	private String whereParentIdIs(Uri uri) {
		return reference.getLinkToParent() + " = " + parseId(uri);
	}
}
